from django.db import models
from mm.dashboard import fields
import datetime
# Create your models here.

class Machine(models.Model):
    """
    A machine represents a host monitored by the Monit agent.
    Each host has services, platform and server data.  This will
    hold all the monitored host data in the form of pickled field
    to store python objects (nested dicts in this case) directly
    via pickle.
    """

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True, auto_now=True)
    hostname = models.CharField(max_length='100')
    services = fields.PickledObjectField()
    platform = fields.PickledObjectField()
    server = fields.PickledObjectField()
    STATUS_CHOICES = (
        ('O', 'Online'),
        ('D', 'Down/Offline'),
        ('F', 'Failed Services'),
        ('P', 'Problems'),
        ('U', 'Data Pulling Issues'),
    )
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='O')
    

    def __unicode__(self):
        return self.hostname

    def check_time(self):

        lastupdate = self.updated_at
        now = datetime.datetime.now()
        delta = now - lastupdate
        if delta.seconds > 600:
            self.status = 'U'
            self.save()
            return
        else:
            if self.status == 'U' and delta.seconds <= 5:
                self.status = 'O'
                self.save()
            return
         
